package org.dromara.common.encrypt.core

import cn.hutool.core.collection.CollUtil
import cn.hutool.core.util.ReflectUtil
import io.github.oshai.kotlinlogging.KotlinLogging
import org.apache.ibatis.io.Resources
import org.dromara.common.core.constant.Constants
import org.dromara.common.core.utils.ObjectUtils
import org.dromara.common.core.utils.StringUtils
import org.dromara.common.encrypt.annotation.EncryptField
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import org.springframework.core.io.support.ResourcePatternResolver
import org.springframework.core.type.classreading.CachingMetadataReaderFactory
import org.springframework.util.ClassUtils
import java.lang.reflect.Field
import java.util.concurrent.ConcurrentHashMap
import java.util.stream.Collectors

/**
 * @updater LikeYouDo
 * @date 2025/1/9 10:49
 */
class EncryptorManager(
    /**
     * 构造方法传入类加密字段缓存
     */
    private val typeAliasesPackage: String
) {

    companion object {
        private val log = KotlinLogging.logger {}
    }

    /**
     * 缓存加密器
     */
    private val encryptorMap: MutableMap<Int, IEncryptor> = ConcurrentHashMap()

    /**
     * 类加密字段缓存
     */
    private val fieldCache: MutableMap<Class<*>, Set<Field>> = ConcurrentHashMap()

    /**
     * 获取类加密字段缓存
     */
    fun getFieldCache(sourceClazz: Class<*>?): Set<Field>? {
        return ObjectUtils.notNullGetter(fieldCache) { f -> f[sourceClazz] };
    }

    /**
     * 注册加密执行者到缓存
     *
     * @param encryptContext 加密执行者需要的相关配置参数
     */
    fun registAndGetEncryptor(encryptContext: EncryptContext): IEncryptor? {
        val key = encryptContext.hashCode()
        if (encryptorMap.containsKey(key)) {
            return encryptorMap[key]
        }
        val encryptor: IEncryptor = ReflectUtil.newInstance(encryptContext.algorithm!!.clazz, encryptContext)
        encryptorMap[key] = encryptor
        return encryptor
    }

    /**
     * 移除缓存中的加密执行者
     *
     * @param encryptContext 加密执行者需要的相关配置参数
     */
    fun removeEncryptor(encryptContext: EncryptContext) {
        encryptorMap.remove(encryptContext.hashCode())
    }

    /**
     * 根据配置进行加密。会进行本地缓存对应的算法和对应的秘钥信息。
     *
     * @param value          待加密的值
     * @param encryptContext 加密相关的配置信息
     */
    fun encrypt(value: String, encryptContext: EncryptContext): String {
        if (StringUtils.startsWith(value, Constants.ENCRYPT_HEADER)) {
            return value
        }
        val encryptor = this.registAndGetEncryptor(encryptContext)
        val encrypt = encryptor!!.encrypt(value, encryptContext.encode)
        return Constants.ENCRYPT_HEADER + encrypt
    }

    /**
     * 根据配置进行解密
     *
     * @param value          待解密的值
     * @param encryptContext 加密相关的配置信息
     */
    fun decrypt(value: String, encryptContext: EncryptContext): String {
        if (!StringUtils.startsWith(value, Constants.ENCRYPT_HEADER)) {
            return value
        }
        val encryptor = this.registAndGetEncryptor(encryptContext)
        val str = StringUtils.removeStart(value, Constants.ENCRYPT_HEADER)
        return encryptor!!.decrypt(str)
    }

    /**
     * 通过 typeAliasesPackage 设置的扫描包 扫描缓存实体
     */
    private fun scanEncryptClasses(typeAliasesPackage: String) {
        val resolver = PathMatchingResourcePatternResolver()
        val factory = CachingMetadataReaderFactory()
        val packagePatternArray = StringUtils.splitPreserveAllTokens(
            typeAliasesPackage,
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS
        )
        val classpath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
        try {
            for (packagePattern in packagePatternArray) {
                val path = ClassUtils.convertClassNameToResourcePath(packagePattern)
                val resources = resolver.getResources("$classpath$path/*.class")
                for (resource in resources) {
                    val classMetadata = factory.getMetadataReader(resource).classMetadata
                    val clazz = Resources.classForName(classMetadata.className)
                    val encryptFieldSet = getEncryptFieldSetFromClazz(clazz)
                    if (CollUtil.isNotEmpty(encryptFieldSet)) {
                        fieldCache[clazz] = encryptFieldSet
                    }
                }
            }
        } catch (e: Exception) {
            log.error { "初始化数据安全缓存时出错:$e.message" }
        }
    }

    /**
     * 获得一个类的加密字段集合
     */
    private fun getEncryptFieldSetFromClazz(cls: Class<*>?): MutableSet<Field> {
        var clazz: Class<*>? = cls
        var fieldSet: MutableSet<Field> = HashSet()
        // 判断clazz如果是接口,内部类,匿名类就直接返回
        if (clazz != null) {
            if (clazz.isInterface || clazz.isMemberClass || clazz.isAnonymousClass) {
                return fieldSet
            }
        }
        while (clazz != null) {
            val fields = clazz.declaredFields
            fieldSet.addAll(listOf(*fields))
            clazz = clazz.superclass
        }
        fieldSet = fieldSet.stream()
            .filter { field ->
                field.isAnnotationPresent(EncryptField::class.java) &&
                    field.type == String::class.java
            }
            .collect(Collectors.toSet())
        for (field in fieldSet) {
            field.isAccessible = true
        }
        return fieldSet
    }
}
